package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ModelDeploymentContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ModelDeploymentPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.ModelCustomConfigDomain;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public abstract class SaveModelAuthAbstractProcessor implements ModelDeploymentPostProcessor {
    @Override
    public void process(ModelDeploymentContext context) {
        String modelAuthKey = getModelAuthKey(context);
        saveModelAuth(modelAuthKey,context);
    }

    protected abstract String getModelAuthKey(ModelDeploymentContext context);

    protected void saveModelAuth(String key,ModelDeploymentContext context){
        JsonNode modelJson = context.getModelJson();
        JsonNode modelProperties = modelJson.get("properties");
        JsonNode modelAuthObj = modelProperties.get(key);
        if (Objects.nonNull(modelAuthObj)){
            String modelAuthValue = modelAuthObj.textValue();
            ModelCustomConfigDomain modelCustomConfigDomain = new ModelCustomConfigDomain();
            modelCustomConfigDomain.setDeploymentId(context.getDeployId());
            modelCustomConfigDomain.setType(key);
            modelCustomConfigDomain.setNodeCode(context.getModel().getKey());
            modelCustomConfigDomain.setConfig(modelAuthValue);
            modelCustomConfigDomain.save();
        }
    }
}
